package com.jcms.cms.action.front;

import static com.jcms.cms.Constants.TPLDIR_INDEX;
import static com.jcms.cms.Constants.TPLDIR_PARCEL;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.jcms.cms.action.front.bind.ParcelDetail;
import com.jcms.cms.entity.main.CmsSite;
import com.jcms.cms.entity.main.CmsUser;
import com.jcms.cms.entity.parcel.CourierCompany;
import com.jcms.cms.entity.parcel.Order;
import com.jcms.cms.entity.parcel.Parcel;
import com.jcms.cms.manager.parcel.CourierCompanyManager;
import com.jcms.cms.manager.parcel.OrderManager;
import com.jcms.cms.manager.parcel.PriceDicManager;
import com.jcms.cms.web.CmsUtils;
import com.jcms.cms.web.FrontUtils;

@Controller
public class ParcelAct {

	private static final Logger log = LoggerFactory.getLogger(VoteAct.class);
	
	public static final String PARCEL_INDEX = "tpl.parcelIndex";
	public static final String PARCEL_COMPANY = "tpl.parcelCompany";
	public static final String PARCEL_DETAIL = "tpl.parcelDetail";
	public static final String PARCEL_PAY = "tpl.parcelPay";
	public static final String INDEX = "tpl.index";
	
	@Autowired
	private CourierCompanyManager courierCompanyManager;
	
	@Autowired
	private PriceDicManager priceDicManager;
	
	@Autowired
	private OrderManager orderManager;
	
	@RequestMapping(value = "/{bar}_index.jspx", method = RequestMethod.GET)
	public String index(@PathVariable("bar") String bar,HttpServletRequest request, ModelMap model) {
		model.put("bar",bar);
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		return FrontUtils.getTplPath(request, site.getSolutionPath(),
				TPLDIR_PARCEL, PARCEL_INDEX);
	}
	
	@RequestMapping(value = "quote.jspx", method={RequestMethod.GET,RequestMethod.DELETE,RequestMethod.PUT})
	public String quote(HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		return "redirect:/";
	}
	
	@RequestMapping(value = "quote.jspx", method=RequestMethod.POST)
	public String quote(@RequestParam("weight") String[] weight,
			@RequestParam("destination") String destination,
			@RequestParam("length") String[] length,
			@RequestParam("width") String[] width,
			@RequestParam("height") String[] height,HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		List<Parcel> parcels = new ArrayList<Parcel>();
		for(int i=0; i<weight.length; i++) {
			Parcel parcel = new Parcel();
			parcel.setWeight(Double.parseDouble(weight[i]));
			parcel.setLength(Double.parseDouble(length[i]));
			parcel.setWidth(Double.parseDouble(width[i]));
			parcel.setHeight(Double.parseDouble(height[i]));
			parcels.add(parcel);
		}
		request.getSession().setAttribute("quote_parcels", parcels);
		//查询所有快递公司
		List<CourierCompany> allCompany = courierCompanyManager.getAll();
		calcPrice(allCompany,parcels);
		model.put("allCompany", allCompany);
		if(destination.equals("zh")) {
			model.put("bar","uc");
		} else if(destination.equals("uk")) {
			model.put("bar","uu");
		}
		FrontUtils.frontData(request, model, site);
		return FrontUtils.getTplPath(request, site.getSolutionPath(),
				TPLDIR_PARCEL, PARCEL_COMPANY);
	}
	
	private void calcPrice(List<CourierCompany> allCompany, List<Parcel> parcels) {
		for(CourierCompany cc : allCompany) {
			double totalPrice = calcPrice(parcels, cc);
			cc.setPrice(totalPrice);
		}
	}

	private double calcPrice(List<Parcel> parcels, CourierCompany cc) {
		double totalPrice = 0d;
		for(Parcel p : parcels) {
			totalPrice += calcPrice(cc, p);
		}
		return totalPrice;
	}

	private double calcPrice(CourierCompany cc, Parcel p) {
		//计算体积重量
		double w1 = p.getLength() * p.getWidth() * p.getHeight() / 5000D;
		//取实际重量和体积重量最大值
		double w = Math.max(w1, p.getWeight());
		//查询价格
		double price = priceDicManager.getPriceByCompanyAndWeight(cc.getId(),w);
		if(w > 30) {
			double addPrice = (w - 30)/0.5 * 1.25;
			price += addPrice;
		}
		return price;
	}
	
	@RequestMapping(value = "detail.jspx",method={RequestMethod.GET,RequestMethod.DELETE,RequestMethod.PUT})
	public String detail(HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		return "redirect:/";
	}
	
	@RequestMapping(value = "detail.jspx",method={RequestMethod.POST})
	public String detail(HttpServletRequest request, ModelMap model, @RequestParam("companyId") String companyId,@RequestParam("bar") String bar) {
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		CourierCompany company = courierCompanyManager.getCompanyById(companyId);
		if(null == company) {
			return "redirect:/";
		}
		model.put("company", company);
		model.put("bar",bar);
		if(null != request.getSession().getAttribute("quote_parcels")) {
			@SuppressWarnings("unchecked")
			List<Parcel> parcels = (List<Parcel>) request.getSession().getAttribute("quote_parcels");
			for(Parcel parcel : parcels) {
				parcel.setPrice(calcPrice(company,parcel));
			}
			company.setPrice(calcPrice(parcels, company));
//			request.getSession().removeAttribute("quote_parcels");
			model.put("parcels", parcels);
		} else {
			return "redirect:/parcelError.jspx";
		}
		return FrontUtils.getTplPath(request, site.getSolutionPath(),
				TPLDIR_PARCEL, PARCEL_DETAIL);
	}
	
	@RequestMapping(value = "order.jspx",method={RequestMethod.GET,RequestMethod.DELETE,RequestMethod.PUT})
	public String order(HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		return "redirect:/";
	}
	
	@RequestMapping(value = "order.jspx",method={RequestMethod.POST})
	public String order(HttpServletRequest request, ModelMap model, 
			@RequestParam("companyId") String companyId,@RequestParam("bar") String bar,Order order,
			ParcelDetail pd) {
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		model.put("bar",bar);
		Set<Parcel> parcels = pd.bindParcels(order);
		CourierCompany company = courierCompanyManager.getCompanyById(companyId);
		order.setCourierCompany(company);
		CmsUser user = CmsUtils.getUser(request);
		order.setUser(user);
		if(bar.equals("uc")) {
			order.setDestination("中国");
		} else if(bar.equals("uu")) {
			order.setDestination("英国");
		}
		order.setIsPay(Order.IS_NOT_PAY);
		order.setPaymentMoney(calcPrice(new ArrayList<Parcel>(parcels), company));
		if(null != order.getIsNeedInsurance() && order.getIsNeedInsurance().intValue() == Order.NEED_INSURANCE) {
			//保险费
		}
		order.setParcelNum(parcels.size());
		int i = orderManager.save(order);
		return "redirect:/jumpToPay.jspx";
	}
	
	@RequestMapping(value = "jumpToPay.jspx")
	public String jumpToPay(HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		return FrontUtils.getTplPath(request, site.getSolutionPath(),
				TPLDIR_PARCEL, PARCEL_PAY);
	}
	
	@RequestMapping(value = "parcelError.jspx",method=RequestMethod.GET)
	public String parcelError(HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		model.put("noLogin", "false");
		model.put("href", site.getContextPath());
		return FrontUtils.getTplPath(request, site.getSolutionPath(),
				TPLDIR_INDEX, INDEX);
	}
	
	@RequestMapping(value = "toLogin.jspx",method=RequestMethod.GET)
	public String toLogin(HttpServletRequest request, ModelMap model) {
		CmsSite site = CmsUtils.getSite(request);
		FrontUtils.frontData(request, model, site);
		model.put("noLogin", "true");
		model.put("href", site.getContextPath());
		return FrontUtils.getTplPath(request, site.getSolutionPath(),
				TPLDIR_INDEX, INDEX);
	}
}
